package com.huatai.manage.aop.aspct;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huatai.common.api.R;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.manage.service.TbTrialInfoService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.huatai.manage.common.constant.ComConstant.*;

/**
 * @ClassName IsExistAspect
 * @Description TODO 校验试验id：trialId是否存在
 * @Author luoxc
 * @Date 2023/3/20 13:31
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class CheckTrialIdAspect {

	@Autowired
	private TbTrialInfoService trialInfoService;

//	@Pointcut("@annotation(com.huatai.manage.aop.annotation.TrialIdIsExist)")
//	private void checkCut() {
//	}

	@Around("@annotation(com.huatai.manage.aop.annotation.TrialIdIsExist)")
	public R checkTrialId(ProceedingJoinPoint joinPoint) {
		Object args = joinPoint.getArgs()[0];
		JSONObject jsonObject = JSONUtil.parseObj(args);
		boolean exist = trialInfoService.isExist((String) jsonObject.get(TRIAL_ID));
		try {
			if (exist) {
				joinPoint.proceed();
				return R.status(true);
			} else {
				log.info("试验id为：{}不存在！", jsonObject.get(TRIAL_ID));
				return R.fail("试验id为：" + jsonObject.get(TRIAL_ID) + "不存在！");
			}
		} catch (Throwable e) {
			throw new ServiceException(e.getMessage());
		}
	}
}
